package com.imau.brand.common.handler;

import com.alibaba.fastjson.JSON;
import com.imau.brand.common.entity.ResultCode;
import com.imau.brand.common.entity.ResultEntity;
import com.imau.brand.common.exception.CommonException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/BaseExceptionHandler")
public class BaseExceptionHandler extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置统一编码
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        // Analyze the servlet exception - www.yiibai.com
        //https://www.runoob.com/servlet/servlet-exception-handling.html
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Integer  statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String  servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
        System.out.println("statusCode="+statusCode);
        System.out.println("servletName="+servletName);
        //统一响应异常结果

        ResultEntity error = this.errorHandeler(request,response,throwable);
        String strJson = JSON.toJSONString(error);
        response.getWriter().write(strJson);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public ResultEntity errorHandeler(HttpServletRequest request, HttpServletResponse response, Throwable e) {

        if(e.getClass() == CommonException.class)
        {
            //类型转型
            CommonException ce = (CommonException) e;
            ResultEntity result = new ResultEntity(ce.getResultCode());
            return result;

        }else{

            ResultEntity result = new ResultEntity(ResultCode.SERVER_ERROR);
            return result;
        }
    }
}
